package org.bot.plugin.data.event;

import org.bot.api.event.DataStorage;
import org.bot.api.event.EventName;
import org.bot.api.event.Events;
import org.bot.api.flow.FlowNode;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 沧月
 * @create 0028 2023/9/28 14:43
 * @description <字符串迭代器>
 */

@Component
@EventName("字符串迭代器")
public class DataStringIteration implements Events {

    @Override
    public Object exec(FlowNode note, DataStorage data) {
        String arg = note.getArg();
        StringIteration stringIteration;
        if (note.getExtendAttr() == null) {
            stringIteration = new StringIteration(arg);
            note.setExtendAttr(stringIteration);
        } else {
            stringIteration = (StringIteration) note.getExtendAttr();
        }
        return stringIteration.getString();
    }


    class StringIteration { ///div/xx/yy/div[{#8}]/div[0]/a/div[{#4}]
        private Pattern pattern = Pattern.compile("\\{#(\\d+)\\}");

        List<Integer> iterationIndex = new ArrayList<>();

        private String oldStr;
        private String newStr;

        public StringIteration(String str) {
            this.oldStr = str;
            this.analysis();
        }


        public String getString() {
            String tmp = this.newStr;
            for (int i = 0; i < iterationIndex.size(); i++) {
                int tmpIndex = iterationIndex.get(i);
                tmp = tmp.replace("{#" + i + "}", String.valueOf(tmpIndex));
                iterationIndex.set(i, tmpIndex + 1);
            }
            return tmp;
        }


        private void analysis() {
            Matcher matcher = pattern.matcher(this.oldStr);
            int index = 0;
            // 提取标识中的数字，并替换为{#索引}
            StringBuffer result = new StringBuffer();
            while (matcher.find()) {
                String matched = matcher.group(1);
                int number = Integer.parseInt(matched);
                iterationIndex.add(number);

                // 替换标识为{#索引}
                matcher.appendReplacement(result, "{#" + index + "}");
                index++;
            }
            matcher.appendTail(result);
            this.newStr = result.toString();
        }
    }

}
